package com.realsatan.gae.wtm;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import com.realsatan.gae.wtm.IndexContent;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import com.google.appengine.api.users.User; 
import com.google.appengine.api.users.UserService; 
import com.google.appengine.api.users.UserServiceFactory;
import javax.jdo.PersistenceManager;
import com.google.appengine.api.memcache.*;

import com.realsatan.gae.wtm.Message;
import com.realsatan.gae.gwttest.shared.FieldVerifier;
import com.realsatan.gae.wtm.PMF;


public class Wtm extends HttpServlet {

	private static String CACHE_CONTENT_STRING = "contentString";
	private static String ADMIN = "realsatan@realsatan.com";
	
	private MemcacheService memcache = MemcacheServiceFactory.getMemcacheService();
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
 		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		String action = request.getParameter("action");
		//无动作，显示内容
		if(action == null) {
			
		}
		else {
			//用户登陆验证
			if(user == null) {
				response.sendRedirect(userService.createLoginURL(request.getRequestURI()));
				return;
			}
			
			//提交
			if(action.equalsIgnoreCase("commit")) {
				Date date = new Date();
				String message = request.getParameter("message");
				message = FieldVerifier.escapeHtml(message);
				//有提交内容时才持久化
				if(message != null && message !="" ) {
					String query = "SELECT FROM " + Message.class.getName() +" order by date desc range 0,1";
					@SuppressWarnings("unchecked")
					List<Message> floorMessage = (List<Message>)pm.newQuery(query).execute();
					int floor = 1;
					if(!floorMessage.isEmpty()) {
						floor = floorMessage.get(0).getFloor() + 1;
					}
					
					Message messObject = new Message(floor, user, message, date);
					
					try {
						pm.makePersistent(messObject);
						memcache.delete(CACHE_CONTENT_STRING);
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						pm.close();
					}
				}
			}
			
			//删除条目 ,action 参数为del,ID为NULL和空值不合完整性
			else if(action.equalsIgnoreCase("del")) {
				String id = request.getParameter("id");
				if(id != null && id != "") {
					try {
						Long longId = Long.parseLong(id);
						Message messageObject2 = pm.getObjectById(Message.class, longId);
						if(user.equals(messageObject2.getUser()) || user.getEmail().equalsIgnoreCase(ADMIN)){
							pm.deletePersistent(messageObject2);
							memcache.delete(CACHE_CONTENT_STRING);
						} else {
							//无删除权限
						}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						pm.close();
					}
				}
	
			}
		}
		
		doDisplay(request, response);
	}
	
	private void doDisplay(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		IndexContent content = new IndexContent();
		
		if(request.getParameter("message") == null) {
			content.setContent("No Posts!");
		} else {
			content.setContent(request.getParameter("message"));
		}
		
		//查找缓存
		if(memcache.contains(CACHE_CONTENT_STRING)) {
			content.setContent((String)memcache.get(CACHE_CONTENT_STRING));
		} else {
			//未缓存
			String query = "select from " + Message.class.getName() +" order by date desc range 0,100";
			
			@SuppressWarnings("unchecked")
			List<Message> messages = (List<Message>)pm.newQuery(query).execute();
			String contentString = "";
			
			//判断是否无任何数据
			if (messages.isEmpty()) {
				contentString += "<p>Now blank.</p>";
			} else {
				int messageNum = messages.size();
				contentString += "<p>本页显示消息：" + messageNum + "</p>";
				
				for(int i = 0 ; i < messageNum ; i++){
					Message m = messages.get(i);
					String userName;
					if(m.getUser() == null) {
						userName = "匿名用户";
					} else {
						userName = m.getUser().getNickname();
					}
					Date date = m.getDate();
					DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.CHINA);
					df.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
					
					contentString += "<div class='messageTitle'>";
					contentString += "<div class='lineleft'><b>" + m.getFloor() + "层 - "
		 						+ userName + "</b> (" + df.format(date) + "):　　　　</div>";
		 			contentString += "<div class='lineright'><a href='/wtm/index.html?action=del&id=" + m.getId() + "'>删</a>";
		 			contentString += "</div></div><div class='clear'></div>";
		 			contentString += "<div class='message'>" + m.getMessage() + "</div>";
				}
			}
			content.setContent(contentString);
			pm.close();
			
			//放入缓存
			memcache.put(CACHE_CONTENT_STRING , contentString);
		}
		
		request.setAttribute("sendcontent", content);
		try {
			request.getRequestDispatcher("wtm.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		doPost(request, response);
	}
}
